const network_utils = require('../../../../../http/NetworkUtils.js');
const constants = require('../../../../../common/Constants.js');
const umfUtils = require('../../../../../utils/UmfUtils.js');
const UmfToast = require('../../../../../utils/UmfToast.js');
import PageRouter from '../../../../../utils/PageRouter';

var app = getApp();
let optionsData = null;
let requestPageSize = "10";
//加载更多方式
let pageNo = null;
let fromPage = '';

const PayTypeAll = "0";
const PayTypeWeiXin = "1";
const PayTypeAlipay = "2";
const PayTypeWePub = "3";
const posWeiXin = "3301",posAlipay="3501",posDebitCard="00",posCreditCard="02",posAllPayType="1111";

const PayAllMaps = {
    [PayTypeWeiXin]: "立马付-微信",
    [PayTypeAlipay]: "立马付-支付宝",
    [PayTypeWePub]: "微信公众号支付"
};
const posPayAllMaps = {
  [posWeiXin]:"微信",
  [posAlipay]:"支付宝",
  [posDebitCard]:"借记卡",
  [posCreditCard]:"贷记卡"
}

Page({
    data: {
        payArray: [],
        isHiddenMenu: true,
        hasMore: false,
        productId:0,  //产品号/当前tab号 0 立马付   1POS  
        //默认全选
        selectAll: true,
        payMaps: PayAllMaps,
        payType: PayTypeAll,
        //Q4新增POS机
        swipertab: [{ name: '立马付交易', tabIndex: 0 }, { name: 'POS机交易', tabIndex: 1 }],
        // currtabIndex: 1  //当前tab号
    },

    onLoad: function (options) {
        pageNo = 0;
        optionsData = JSON.parse(options.optionsData);
        fromPage = JSON.parse(options.params).fromPage;
        wx.setNavigationBarTitle({
            title: (optionsData.payTime || "")
        });
        // this.requestTotalAmt()
        if (optionsData.posReportId){
          this.setData({
            isShowSwipertab: true
          });
        }
        this.showWithPayType();
        this._netWorkRequest();
    },
    /**
        * @Explain：选项卡点击切换 接入POS
        */
    tabSwitch: function (e) {
      //当前选中productId == 点击按钮 不做处理
       if (this.data.productId == e.currentTarget.dataset.current) {
         return;
        }
      pageNo = 0;
      //TODO  一个表示立马付或者POS的参数传给后台做网络请求
      if (e.currentTarget.dataset.current == 0) {
        //立码付
        this.setData({
          productId:0,
          selectAll: true,
          payMaps: PayAllMaps,
          payType: PayTypeAll,
        })
        this._netWorkRequest();
      } else {
        //pos机
        this.setData({
          productId:1,
          selectAll: true,
          payMaps: posPayAllMaps,
          payType: "",
        });
        this._posNetworkRequest();
      }
    /*  if (this.data.productId != e.currentTarget.dataset.current) {
        this.setData({
          productId: e.currentTarget.dataset.current
        })
        // //网络请求TODO
       
      }*/
      //网络请求
      // this.onRefresh();
    },

    /**
     * 通过payType设置payMaps和selectAll
     */
    showWithPayType: function () {
        if (this.data.payType === PayTypeAll) {
            this.setData({
                selectAll: true,
                // payMaps: this.data.productId == 0 ? PayAllMaps : posPayAllMaps
                payMaps: PayAllMaps
            });
        } else {
            let payMapsBack = {};
            let paymaps = this.data.payType.split(',');
            for (let payType in paymaps) {
                payMapsBack[payType] = PayAllMaps[payType]
            }
            this.setData({
                selectAll: false,
                payMaps: payMapsBack
            });
        }
    },

    /**
     * 全选
     * @param bool
     * @returns {*}
     */
    changeAll: function(bool) {
        if (bool) {
            this.setData({
              // payMaps: this.data.productId == 0 ? PayAllMaps : posPayAllMaps,
              payMaps: PayAllMaps,
                selectAll: true
            });
        } else {
            this.setData({
                payMaps: {},
                selectAll: false
            });
        }

    },

    catchtap: function () {},

    /**
     * 选择支付方式
     * @param list
     * @returns {*}
     */
    onMapChange: function(list) {
        let payMapsChange = {};
        for (let value of list) {
          // payMapsChange[value] = this.data.productId == 0 ? PayAllMaps[value] : posPayAllMaps[value];
          payMapsChange[value] = PayAllMaps[value]
        }
        this.setData({
            payMaps: payMapsChange,
            // selectAll: list.length === Object.keys(this.data.productId == 0 ? PayAllMaps : posPayAllMaps).length
            selectAll: list.length === Object.keys( PayAllMaps ).length
        });
    },

    tapLayor: function () {
        this.setData({
            isHiddenMenu: !this.data.isHiddenMenu,
        });
    },

    click_add: function () {
        this.setData({
            isHiddenMenu: !this.data.isHiddenMenu,
        })
    },


    //加载更多
    loadMore: function () {
        this._netWorkRequest();
    },

    checkboxChange: function (e) {
        this.onMapChange(e.detail.value);
    },

    checkboxChangeAll: function (e) {
        //全选
        if (e.detail.value.length > 0) {
            this.changeAll(true);
        } else {
            this.changeAll(false);
        }
    },

    radioChange:function(e){
      this.setData({
        payType: e.detail.value
      });
    },

    btnClick: function (e) {
        pageNo = 0;
        let myPayType = "";
        //productId == 1 pos 
        if (this.data.productId == '1'){
          this._posNetworkRequest()
        }else{
            //立马付
            if (this.data.selectAll || Object.keys(this.data.payMaps).length === Object.keys(PayAllMaps).length) {
              myPayType = PayTypeAll;
          } else {
              myPayType = Object.keys(this.data.payMaps).join(',')
          }

          if (!myPayType) {
              wx.showToast({
                  title: '请选择筛选方式',
                  duration: 1000,
              });
              return;
          }

            this.setData({
              isHiddenMenu: true,
              payType: myPayType
            });
            this._netWorkRequest();
        }

       
    },

    cellClick: function (e) {
        var item = this.data.payArray[e.currentTarget.dataset.current];
        let url = './orderDetail/orderDetail';
        let data = {};
        if(this.data.productId==0){
          //立马付FUNC_POS_TRADDETAIL
           data = {
            title: optionsData.title,
            tradeNo: item.tradeNo,
          };
        } else if (this.data.productId==1){
          data = {
            title: optionsData.title,
            tradeNo: item.tradeNo,
            productId: this.data.productId,
            orderDate:item.dateTime,
            storeId: item.storeId
          };
        }      
        PageRouter.wxNavigateTo(fromPage, url, fromPage === 'searchStores' || fromPage === "clerkTransOverview", data);
    },

    //请求交易总计金额和笔数
    // requestTotalAmt:function(){
    //   //TODO  将payType转为：XXX总计
    //   let interfaceNet = constants.Interfaces.FUNC_IMP_TOTALAMT
    //   let params = {
    //     storeId: optionsData.storeId,
    //     orderDate: optionsData.payTime,
    //     payType: this.data.payType,
    //     }
    //     //TODO  将payType转为：XXX总计
    //     if(this.data.productId==1){
    //       interfaceNet = constants.Interfaces.FUNC_POS_TOTALAMT
    //       // params.tranType = TODO  看看这个参数怎么传 payType也得改造
    //     }
    //     network_utils.buildRequest(interfaceNet, params, {
    //     doHttpSucess: function (data) {
    //       if (constants.RetCodes.SUCCESS === data.retCode) {
    //         this.setData({
    //           totalAmt: data.totalAmt,
    //           totalNum: data.totalNum
    //         })
    //         return true;
    //       }
    //       return false;
    //     },
    //     doHttpFailure: (response) => {
    //       return false;
    //     },
    //   }).send();
    // },
  //POS 交易列表查询
    _posNetworkRequest:function(){

      let that = this;
      let interfaceNet = constants.Interfaces.FUNC_POS_TRADINLIST
      let params = {
        storeId: optionsData.storeId,
        date: optionsData.payTime,
        payType: this.data.payType,
        pageNo: pageNo + 1 + '',
        pageSize: requestPageSize,
      };
      network_utils.buildRequest(interfaceNet, params, {
        doHttpSucess: function (data) {
          if (constants.RetCodes.SUCCESS === data.retCode) {
            pageNo++;

            let hasMore = data["resultList"].length === parseInt(requestPageSize);
            !hasMore && UmfToast.showToast("已经加载完所有数据");
            that.setData({
              hasMore: hasMore,
              payArray: _dataFormate(that, data["resultList"], that.data.payArray),
            });
            return true;
          }
          return false;
        },
        doHttpFailure: (response) => {
          that.setData({
            isHiddenMenu: true,
          });
          return false;
        },
      }).send();
    },
    //立马付 交易列表
    _netWorkRequest: function () {
        let that = this;
        let interfaceNet = constants.Interfaces.FUNC_Merchant_DayTrading
        let params = {
            storeId: optionsData.storeId,
            date: optionsData.payTime,
            payType: this.data.payType,
            pageNo: pageNo + 1 + '',
            pageSize: requestPageSize,
        };
        // if (this.data.productId == 1) {
        //   interfaceNet = constants.Interfaces.FUNC_POS_TRADINLIST
        //   let tranType='',cardType=''
        //   if(this.data.payType!="1111"){
        //     let payTypeArr = this.data.payType.split(",")
        //     for (let i = 0; i < payTypeArr.length; i++) {
        //       if (payTypeArr[i] == '3301') {tranType+="3301,"}
        //       else if (payTypeArr[i] == '3501') {tranType+= "3501,"}
        //       else if (payTypeArr[i] == '00') { 
        //         tranType += "0,"
        //         cardType+="00,"
        //         }
        //       else if (payTypeArr[i] == '02') { 
        //         tranType += "0,"; 
        //         cardType += "02," 
        //         }
        //     }
        //   }   
        //   params={
        //     storeId: optionsData.storeId,
        //     orderDate: optionsData.payTime,
        //     currentPage: pageNo + 1 + '',
        //     pageSize: requestPageSize,
        //     tranType: tranType,
        //     cardType: cardType
        //   }
        // }
             
        network_utils.buildRequest(interfaceNet, params, {
            doHttpSucess: function (data) {
                that.setData({
                    isHiddenMenu: true,
                });
                if (constants.RetCodes.SUCCESS === data.retCode) {
                    pageNo++;

                    let hasMore = data["tradeList"].length === parseInt(requestPageSize);
                    !hasMore && UmfToast.showToast("已经加载完所有数据");
                    that.setData({
                        hasMore: hasMore,
                        payArray: _dataFormate(that,data["tradeList"], that.data.payArray),
                    });
                    return true;
                }
                return false;
            },
            doHttpFailure: (response) => {
                that.setData({
                    isHiddenMenu: true,
                });
                return false;
            },
        }).send();
    },

});

//格式化数据
function _dataFormate(page, tradeList, data) {
    let payDataArray = pageNo === 1 ? [] : data;
    //数据格式化
    for (let i = 0; i < tradeList.length; i++) {
        tradeList[i]["amount"] = umfUtils.fentoyuan(tradeList[i]["amount"]);
        tradeList[i]["refundAmt"] = umfUtils.fentoyuan(tradeList[i]["refundAmt"]);
        if (page.data.productId !="1"){
          tradeList[i]["payTypeName"] = PayAllMaps[tradeList[i]["payType"]].split('-')[0];
        }
        
        if (tradeList[i]["payType"] == "微信支付"){
          tradeList[i]["posPayUserName"] = "微信用户";
        } else if (tradeList[i]["payType"] == "支付"){
          tradeList[i]["posPayUserName"] = "支付宝用户";
        }else {
          tradeList[i]["posPayUserName"] = tradeList[i]["cardNo"] + "("+tradeList[i]["cardType"]+")";
       }
       //pos +\-号判断
        if (tradeList[i]["payType"] == "退货" || tradeList[i]["payType"] == "撤销" || tradeList[i]["payType"] == "预授权申请撤销" || tradeList[i]["payType"] =="预授权完成撤销"){
          tradeList[i]["posPayState"] =   "-" ;
        }else{
          tradeList[i]["posPayState"] = "+";
        }
       
        payDataArray.push(tradeList[i]);
    }
    return payDataArray;
}